import 'reflect-metadata'
import { app, shell, BrowserWindow, ipcMain, globalShortcut, screen } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { initDataBase } from './db/data-source'
import { ipcMainFunc } from './ipMain'

var mainWindow = null
let frame = true
function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1366,
    height: 736,
    // minHeight: 500,
    // minWidth: 1000,
    // maxHeight: 900,
    // maxWidth: 1600,
    frame: frame,
    resizable: false,
    transparent: true,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      contextIsolation: true
    }
  })
  // 注册一个 'Ctrl+F12' 快捷键监听器
  globalShortcut.register('Ctrl+F12', () => {
    console.log(111)

    // mainWindow.webContents.openDevTools()
  })
  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  setTimeout(() => {
    mainWindow.webContents.openDevTools()
  }, 1000)

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  // mainWindow.webContents.on('dom-ready', () => {
  //   mainWindow.webContents.executeJavaScript(`
  //     document.addEventListener('mousemove', (event) => {
  //       console.log('Mouse moved inside window:', event);
  //     });
  //     document.addEventListener('keyup', (event) => {
  //       console.log('Mouse moved inside window:', event);
  //     });
  //   `)
  // })
}

app.whenReady().then(async () => {
  startListeningToMouseMove()
  electronApp.setAppUserModelId('com.electron')
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  createWindow()
  initDataBase()

  // 注册通信方法
  ipcMainFunc()
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    globalShortcut.unregisterAll()
    app.quit()
  }
})

function startListeningToMouseMove() {
  console.log(screen)

  // // 获取主屏幕
  // const mainScreen = screen.getPrimaryDisplay()

  // // 开始监听鼠标移动事件
  // mainScreen.on('mousemove', (event, point) => {
  //   console.log(`Mouse moved to: ${point.x}, ${point.y}`)
  // })
}
